<!--组件库管理左侧-->
<template>
	<el-container class="list componentList-page">
		<el-aside width="220px">
			<ul class="menu">
				<li
					:index="item.categoryValue"
					:key="item.categoryValue"
					v-for="item in typeList"
					:class="{ 'is-active': item.categoryValue === activeName }"
					@click="handleSelect(item.categoryValue)"
				>
					<i class="el-icon-s-order"></i>
					{{ item.categoryKey }}
				</li>
			</ul>
		</el-aside>
		<el-container>
			<el-header class="content__header">
				<div class="content__box content__nav">
					<div class="content_ads">
						<el-radio-group v-model="classify" size="small" @input="handleClassify">
							<el-radio-button label="CHART"> 图表 </el-radio-button>
							<el-radio-button label="FORM">表单</el-radio-button>
							<el-radio-button label="MEDIA">媒体</el-radio-button>
							<el-radio-button label="TARGET">指标</el-radio-button>
							<el-radio-button label="TABLE">表格</el-radio-button>
							<el-radio-button label="OTHER">其它</el-radio-button>
						</el-radio-group>
					</div>
					<div class="content__page">
						<el-radio-group v-model="presentationStyle" size="mini">
							<el-radio-button label="缩略图版"></el-radio-button>
							<el-radio-button label="纯表格版"></el-radio-button>
						</el-radio-group>
						<div class="visualName">
							<el-input placeholder="请输入组件名称" v-model="visualName" class="input-with-select" clearable size="small" @clear="searchVisualList('')">
								<el-button slot="append" icon="el-icon-search" @click="searchVisualList(visualName)"></el-button>
							</el-input>
						</div>
					</div>
				</div>
			</el-header>
			<el-main class="content">
				<div v-loading="loading" element-loading-text="组件库列表加载中，请稍后..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
					<avue-crud ref="crud" v-if="presentationStyle == '纯表格版'" :data="list" :option="visualTableOption" @selection-change="selectionChange">
						<template slot-scope="{ row, index }" slot="menuLeft">
							<el-button type="danger" size="small" icon="el-icon-delete" plain @click="handleDelete">删 除 </el-button>
						</template>
						<template slot-scope="{ row, index }" slot="menu">
							<el-button type="text" icon="el-icon-edit" size="small" @click="handleEdit(row, index)">编辑</el-button>
							<el-button type="text" icon="el-icon-delete" size="small" @click="handleDel(row, index)">删除</el-button>
						</template>
						<template slot="thumbnail" slot-scope="{ row }">
							<el-image style="width: 100px; height: 50px" :src="row.thumbnail" :preview-src-list="[row.thumbnail]"> </el-image>
						</template>
					</avue-crud>
					<div v-else class="content__box">
						<div class="content__item" v-for="(item, index) in list" :key="index" @mouseover="item._menu = true" @mouseout="item._menu = false">
							<div class="content__info">
								<img v-if="item.thumbnail" :src="item.thumbnail" alt="" />
							</div>
							<div class="content__main">
								<span class="content__name" :title="item.title">
									{{ item.name }}
								</span>
								<div class="content__menulist"></div>
							</div>
							<div class="content__main">
								<span class="content__time">
									{{ item.updateTime }}
								</span>
								<div class="content__menulist">
									<div class="content__view"></div>
									<span
										class="content__status"
										:class="{
											'content__status--active': item.status
										}"
									>
										{{ item.status ? '已发布' : '未发布' }}
									</span>
								</div>
							</div>
							<div class="content__menu" v-show="item._menu">
								<div class="content__right">
									<el-tooltip content="分享">
										<i class="el-icon-share" @click="handleShare(item, index)"></i>
									</el-tooltip>
								</div>
								<el-drawer :title="share.title" :append-to-body="true" :modal-append-to-body="true" :visible.sync="share.visible" direction="rtl">
									<span>用户列表</span>
									<p>后续功能</p>
								</el-drawer>
								<div class="content__btn" @click="handleEdit(item)">编辑</div>
								<div class="content__list">
									<!-- <el-tooltip content="修改">
                                        <i
                                            class="el-icon-edit"
                                            @click="handleUpdate(item, index)"
                                        ></i>
                                    </el-tooltip> -->
									<el-tooltip content="删除">
										<i class="el-icon-delete" @click="handleDel(item, index)"></i>
									</el-tooltip>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="pagination">
					<el-pagination
						v-if="page.total > 0"
						layout="total, sizes, prev, pager, next, jumper"
						background
						size="mini"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:page-size="page.size"
						:page-sizes="[15, 30, 40, 50]"
						:current-page.sync="page.page"
						:total="page.total"
					>
					</el-pagination>
				</div>
			</el-main>
		</el-container>
		<el-dialog title="编辑" :visible.sync="dialogPublishFormVisible" :append-to-body="true" :close-on-click-modal="false" custom-class="publish-comp-dialog">
			<avue-form v-model="publishForm" :option="publishOption" @submit="publishSubmit" @error="error">
				<template slot-scope="{ disabled, size }" slot="componentJson">
					<monaco-editor v-model="publishForm.componentJson" height="400" language="json"></monaco-editor>
				</template>
				<template slot-scope="{ disabled, size }" slot="thumbnail">
					<el-upload
						ref="upload"
						class="upload-demo"
						:on-success="handleThumbnailSuccess"
						:action="basePrefix + '/visual/put-file'"
						:on-remove="handleThumbnailRemove"
						:file-list="fileList"
						:limit="1"
						list-type="picture"
					>
						<el-button size="small" type="primary">点击上传</el-button>
					</el-upload>
				</template>
			</avue-form>
		</el-dialog>
	</el-container>
</template>
<script>
import { getList, getCompDetail, delComp, addComp } from '@/api/componentList';
import MonacoEditor from '@/page/components/editor';
import { getObj } from '@/api/visual';
import { basePrefix } from '@/config';
import { viewHtml } from '@/utils/html';
import { mapState, mapGetters } from 'vuex';
export default {
	name: 'componentList',
	components: {
		MonacoEditor
	},
	data() {
		return {
			selectionList: [],
			fileList: [],
			basePrefix: basePrefix,
			share: {
				title: '',
				visible: false
			},
			loading: false,
			visualName: '',
			classify: 'CHART',
			typeList: [
				{
					// componentType
					categoryKey: '基础组件',
					categoryValue: 'BASE'
				},
				{
					categoryKey: '自定义组件',
					categoryValue: 'CUSTOMIZED'
				},
				{
					categoryKey: '业务组件',
					categoryValue: 'BUSINESS'
				}
			],
			page: {
				page: 1,
				size: 15,
				total: 0
			},
			presentationStyle: '缩略图版',
			visualTableOption: {
				rowKey: 'id',
				selection: true,
				tip: false,
				addBtn: false,
				delBtn: false,
				columnBtn: false,
				refreshBtn: false,
				editBtn: false,
				menuWidth: 200,
				menu: true,
				// height: 520,
				index: true,
				indexLabel: '序号',
				column: [
					{
						label: '组件名称',
						prop: 'name'
					},
					{
						label: '缩略图',
						prop: 'thumbnail',
						slot: true,
						width: 200
					},
					{
						label: '发布人',
						prop: 'publisher',
						width: 200
					},
					{
						label: '创建时间',
						prop: 'createTime',
						width: 200
					},
					{
						label: '更新时间',
						prop: 'updateTime',
						width: 200
					},
					{
						label: '状态',
						prop: 'status',
						type: 'select',
						width: 100,
						dicData: [
							{
								label: '未发布',
								value: 0
							},
							{
								label: '已发布',
								value: 1
							}
						]
					}
				]
			},
			activeName: '',
			list: [],
			dialogPublishFormVisible: false,
			publishForm: { thumbnail: '' },
			publishOption: {
				labelWidth: 100,
				column: [
					{
						label: '组件名称',
						prop: 'name',
						span: 12,
						rules: [
							{
								required: true,
								message: '请输入组件名称',
								trigger: 'blur'
							}
						]
					},
					{
						label: '组件类型',
						prop: 'componentType',
						type: 'select',
						dicData: [
							{
								label: '基础组件',
								value: 'BASE'
							},
							{
								label: '自定义组件',
								value: 'CUSTOMIZED'
							},
							{
								label: '业务组件',
								value: 'BUSINESS'
							}
						],
						span: 12,
						rules: [
							{
								required: true,
								message: '请输入组件类型',
								trigger: 'blur'
							}
						]
					},
					{
						label: '功能分类',
						prop: 'classify',
						type: 'select',
						dicData: [
							{
								label: '图表',
								value: 'CHART'
							},
							{
								label: '表单',
								value: 'FORM'
							},
							{
								label: '媒体',
								value: 'MEDIA'
							},
							{
								label: '指标',
								value: 'TARGET'
							},
							{
								label: '表格',
								value: 'TABLE'
							},
							{
								label: '其它',
								value: 'OTHER'
							}
						],
						span: 12,
						rules: [
							{
								required: false,
								message: '请输入组件类型',
								trigger: 'blur'
							}
						]
					},
					{
						label: '发布人',
						prop: 'publisher',
						span: 12,
						rules: [
							{
								required: false,
								message: '请输入发布人',
								trigger: 'blur'
							}
						]
					},
					{
						label: '缩略图上传',
						prop: 'thumbnail',
						formslot: true,
						span: 24
					},

					{
						label: '组件json',
						prop: 'componentJson',
						formslot: true,
						span: 24,
						// type: "textarea",
						// minRows: 10,
						// maxRows: 20,
						rules: [
							{
								required: true,
								message: '请输入组件json',
								trigger: 'blur'
							}
						]
					}
				]
			}
		};
	},
	created() {
		this.activeName = this.typeList[0].categoryValue;
		this.getList();
	},
	computed: {
		...mapState(['token', 'tenantId', 'siteId']),
		...mapGetters(['avatar', 'userName', 'userId'])
	},
	methods: {
		selectionChange(list) {
			this.selectionList = list;
		},
		handleDelete() {
			if (this.selectionList.length === 0) {
				this.$message.warning('请选择至少一条数据');
				return;
			}
			this.$confirm('确定将选择数据删除?', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					let ids = this.selectionList.map(s => s.id).join(',');
					return delComp(ids);
				})
				.then(() => {
					this.page.page = 1;
					this.getList();
					this.$message.success('删除成功');
					this.$refs.crud.toggleSelection();
				});
		},
		handleThumbnailRemove(file, fileList) {
			this.fileList = [];
			this.$set(this.publishForm, 'thumbnail', '');
		},
		handleThumbnailSuccess(res, file) {
			if (res && res.code == 200) {
				let url = res.data.link;
				this.fileList = [
					{
						name: this.publishForm.name,
						url: url
					}
				];
				this.$set(this.publishForm, 'thumbnail', url);
			}
		},
		handleSelect(key) {
			this.activeName = key;
			this.page.page = 1;
			this.classify = 'CHART';
			this.getList();
		},
		vaildData(id) {
			const list = [];
			for (var i = 0; i < 20; i++) {
				list.push(i);
			}
			return list.includes(id);
		},
		handleShare(item, index) {
			this.share.visible = true;
			this.share.title = item.name + '组件分享';
		},
		handleDel(item, index) {
			if (this.vaildData(index) && this.$website.isDemo) {
				this.$message.error(this.$website.isDemoTip);
				return false;
			}
			this.$confirm('是否确认永久删除?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					delComp(item.id).then(() => {
						this.list.splice(index, 1);
						this.$message.success('删除成功');
						this.page.page = 1;
						this.getList();
					});
				})
				.catch(() => {});
		},
		handleUpdate(item, index) {
			if (this.vaildData(Number(index)) && this.$website.isDemo) {
				this.$message.error(this.$website.isDemoTip);
				return false;
			}
			this.form = item;
			this.form.category = this.form.category + '';
		},
		handleEdit(item) {
			this.dialogPublishFormVisible = true;
			this.publishForm.id = item.id;
			this.publishForm.name = item.name;
			this.publishForm.componentType = item.componentType;
			this.publishForm.classify = item.classify;
			this.publishForm.thumbnail = item.thumbnail;
			this.fileList = [
				{
					name: item.name,
					url: item.thumbnail
				}
			];
			this.publishForm.componentJson = JSON.stringify(JSON.parse(item.componentJson), null, 2);
			// this.publishForm.componentJson =item.componentJson;
		},
		uploadDelete(file, column) {
			return new Promise((resolve, reject) => {
				this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				})
					.then(() => {
						console.log(file.uid);
						if (file.uid) {
							this.$set(this.publishForm, 'thumbnail', '');
						}
						resolve();
					})
					.catch(() => {
						reject();
						this.$message({
							type: 'info',
							message: '已取消删除'
						});
					});
			});
		},
		// 组件编辑提交
		publishSubmit(form, done) {
			addComp(form)
				.then(res => {
					this.$message.success('组件更新成功！');
					this.dialogPublishFormVisible = false;
					this.page.page = 1;
					this.$refs.upload.clearFiles();
					this.getList();
					done();
				})
				.catch(err => {
					done();
				});
		},

		handleViews(item) {
			getCompDetail(item.id)
				.then(res => {})
				.catch(err => {});
		},

		handleCurrentChange(val) {
			this.page.page = val;
			this.getList();
		},
		handleSizeChange(val) {
			this.page.size = val;
			this.getList();
		},
		getList(category) {
			this.list = [];
			this.loading = true;
			getList({
				name: this.visualName,
				classify: this.classify,
				componentType: category || this.activeName,
				current: this.page.page,
				size: this.page.size
			})
				.then(res => {
					const data = res.data.data;
					this.page.total = data.total;
					this.list = data.records;
					this.initData();
				})
				.finally(() => {
					this.loading = false;
				});
		},
		initData() {
			this.list.forEach((ele, index) => {
				this.$set(this.list[index], '_menu', false);
			});
		},
		searchVisualList(name) {
			this.visualName = name;
			this.getList();
		},
		handleClassify() {
			this.page.page = 1;
			this.getList();
		}
	}
};
</script>
<style lang="scss">
@import '@/styles/list.scss';
.componentList-page.list {
	.content {
		.avue-crud__menu {
			display: block;
		}
		.pagination {
			display: flex;
			justify-content: flex-end;
			margin: 15px 30px 0 0;
		}
	}
}
.publish-comp-dialog {
	margin-top: 5vh !important;
}
</style>
